package com.tdd.tdd;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.util.Arrays;

enum ApiResultStatus {
    /**
     * 成功
     */

    SUCCESS(200),
    /**
     * 失败
     */

    FAILED(400),

    /**
     * 未定义
     */
    UNDEFINED(0);

    public int status;

    public int getStatus() {
        return status;
    }

    ApiResultStatus(int status) {
        this.status = status;
    }
}

class ApiResult<T> {

    private ApiResultStatus status;
    private String message;
    private T data;


    public ApiResult(ApiResultStatus status, String message, T data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    public static <T> ApiResult<T> success(T data) {
        return new ApiResult<>(ApiResultStatus.SUCCESS, "success", data);
    }


}

class EnumSerializer implements JsonSerializer<ApiResultStatus>, JsonDeserializer<ApiResultStatus> {
    // 对象转为Json时调用,实现JsonSerializer<PackageState>接口
    @Override
    public JsonElement serialize(ApiResultStatus state, Type arg1, JsonSerializationContext arg2) {
        return new JsonPrimitive(state.getStatus());
    }

    // json转为对象时调用,实现JsonDeserializer<PackageState>接口
    @Override
    public ApiResultStatus deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
        return Arrays.stream(ApiResultStatus.values())
                .parallel().filter(it -> it.status == json.getAsInt()).findFirst()
                .orElse(ApiResultStatus.UNDEFINED);
    }
}

public class Demo {


    public static void main(String[] args) {

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(ApiResultStatus.class, new EnumSerializer());
        Gson gson = gsonBuilder.create();

        ApiResult<String> apiResult = ApiResult.success("asdf");
        System.out.println(gson.toJson(apiResult));

        System.out.println(gson.fromJson("200", ApiResultStatus.class));
        System.out.println(gson.fromJson("300", ApiResultStatus.class));
    }

}


